from django.shortcuts import render

# Create your views here.
from django.db import transaction
from rest_framework.generics import ListAPIView, GenericAPIView, CreateAPIView
from rest_framework.mixins import RetrieveModelMixin, CreateModelMixin, ListModelMixin, UpdateModelMixin, DestroyModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from .serializers import SpitSerializer, SpitCommentSeriazer, SpitSubmitSerializer, SpitLikeSerializer, SpitCollectionSerializer, SpitLikeActionSerializer, SpitCollectionActionSerializer, SpitCommentLikeActionSerializer, SpitCommentLikeSerializer, SpitCommentCreateSerializer

from .models import spits, spits_comment, spits_Like, spits_collection, spits_comment_Like
from .utils import StandardPageNumberPagination

class SpitList(ListAPIView):
    """吐槽列表"""
    queryset = spits.objects.all().order_by('id')
    serializer_class = SpitSerializer
    pagination_class = StandardPageNumberPagination


class SpitDetail(APIView):
    """吐槽详情"""

    def get(self, request):
        spit_id = request.query_params.get('spit_id')
        spit = spits.objects.get(id=spit_id)
        serializer = SpitSerializer(spit)
        return Response(serializer.data)


class Spit_Comment(GenericViewSet):
    """吐槽评论"""
    queryset = spits_comment.objects.all()
    serializer_class = SpitCommentSeriazer

    def get_queryset(self):
        spit_id = self.request.query_params.get('spits_id')
        return spits_comment.objects.filter(spit_id=spit_id)

    def list(self, request):
        comment = self.get_queryset()
        serializer = self.get_serializer(comment, many=True)
        return Response(serializer.data)


class Spit_Submit(CreateAPIView):
    """吐槽表单提交"""
    serializer_class = SpitSubmitSerializer
    permission_classes = [IsAuthenticated]


class Spit_like(GenericAPIView, ListModelMixin):
    """吐槽点赞"""

    serializer_class = SpitLikeSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        user_id = self.request.query_params.get('user_id')
        return spits_Like.objects.filter(user_id=user_id)

    def get(self, request):
        spit_id = self.get_queryset()
        serializer = self.get_serializer(spit_id, many=True)
        spit_likes = []
        for spit_like in serializer.data:
            spit_likes.append(spit_like['spits_id'])

        return Response({'spit_likes': spit_likes})


class SpitLikeActionView(APIView):
    """吐槽点赞与取消点赞"""
    permission_classes = [IsAuthenticated]

    def post(self, request):
        user = request.user
        serializer = SpitLikeActionSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        spit_id = serializer.validated_data['spits_id']
        action = serializer.validated_data['action']
        instance = spits_Like.objects.filter(user_id=user, spit_id=spit_id)
        if action == 'add':
            with transaction.atomic():
                try:
                    save_id = transaction.savepoint()
                    spit_like = spits_Like.objects.create(
                        user_id=user,
                        spit_id=spit_id
                    )
                    spit_like.save()
                    spit_id.like_count += 1
                    spit_id.save()
                except Exception:
                    transaction.savepoint_rollback(save_id)
                    raise
                else:
                    transaction.savepoint_commit(save_id)
        else:
            instance.delete()
            spit_id.like_count -= 1
            spit_id.save()

        return Response({'message': "ok"})


class Spit_colletion(GenericAPIView, ListModelMixin):

    """吐槽收藏"""

    serializer_class = SpitCollectionSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        user_id = self.request.query_params.get('user_id')
        return spits_collection.objects.filter(user_id=user_id)

    def get(self, request):
        spit_id = self.get_queryset()
        serializer = self.get_serializer(spit_id, many=True)
        spit_collections = []
        for spit_collection in serializer.data:
            spit_collections.append(spit_collection['spit_id'])

        return Response({'spit_collections': spit_collections})


class SpitCollectionActionView(APIView):
        """吐槽收藏与取消收藏"""
        permission_classes = [IsAuthenticated]

        def post(self, request):
            user = request.user
            serializer = SpitCollectionActionSerializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            spit_id = serializer.validated_data['spit_id']
            action = serializer.validated_data['action']
            # print(spit_id.like_count)
            instance = spits_collection.objects.filter(user_id=user, spit_id=spit_id)
            if action == 'add':
                with transaction.atomic():
                    try:
                        save_id = transaction.savepoint()
                        spit_collection = spits_collection.objects.create(
                            user_id=user,
                            spit_id=spit_id
                        )
                        spit_collection.save()

                    except Exception:
                        transaction.savepoint_rollback(save_id)
                        raise
                    else:
                        transaction.savepoint_commit(save_id)
            else:
                instance.delete()

            return Response({'message': "ok"})


class SpitCommentLikeView(GenericAPIView):
    """获取评论点赞信息"""
    serializer_class = SpitCommentLikeSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        user_id = self.request.query_params.get('user_id')
        return spits_comment_Like.objects.filter(user_id=user_id)

    def get(self, request):
        comment_id = self.get_queryset()
        serializer = self.get_serializer(comment_id, many=True)
        comment_likes = []
        for comment_like in serializer.data:
            comment_likes.append(comment_like['comment_id'])

        return Response({'comment_likes': comment_likes})


class SpitCommentLikeActionView(APIView):
    """吐槽评论点赞与取消点赞"""
    permission_classes = [IsAuthenticated]

    def post(self, request):
        serializer = SpitCommentLikeActionSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        comment_id = serializer.validated_data['comment_id']
        action = serializer.validated_data['action']
        user = request.user
        # print(spit_id.like_count)
        instance = spits_comment_Like.objects.filter(user_id=user, comment_id=comment_id)
        if action == 'add':
            with transaction.atomic():
                try:
                    save_id = transaction.savepoint()
                    comment_like = spits_comment_Like.objects.create(
                        user_id=user,
                        comment_id=comment_id
                    )
                    comment_like.save()
                    comment_id.like_count += 1
                    comment_id.save()
                except Exception:
                    transaction.savepoint_rollback(save_id)
                    raise
                else:
                    transaction.savepoint_commit(save_id)
        else:
            instance.delete()
            comment_id.like_count -= 1
            comment_id.save()

        return Response({'message': "ok"})


class SpitCommentCreateView(CreateAPIView):
    serializer_class = SpitCommentCreateSerializer
    permission_classes = [IsAuthenticated]